﻿; (function (global) {
    'use strict';

    global.Timer = function Timer(callback, delay) {

        this.startDate = 0;
        this.isRunning = false;
        this.elapsed = 0;

        this.callback = callback;
        this.delay = delay;
        this.timerId = -1;
    }

    Timer.prototype.start = function (handicap) {
        handicap = handicap || 0;
        this.isRunning = true;
        this.startDate = Date.now() - handicap;

        if (this.callback) {
            this.callback();
            this.timerId = global.setTimeout(this._reminder.bind(this), this.delay);
        }
            
    };

    Timer.prototype.pause = function (ev, cellModel) {
        if (this.isRunning) {
            this.isRunning = false;
            this.elapsed = Date.now() - this.startDate;

            if (this.callback)
                global.clearTimeout(this.timerId);
        }
    };

    Timer.prototype.resume = function (ev, key) {
        if (!this.isRunning) {
            this.isRunning = true;
            this.startDate = Date.now() - this.elapsed;
            this.elapsed = 0;

            if (this.callback) {
                var value = this.getValue();
                var remaining = this.delay - (value % this.delay);
                this.timerId = global.setTimeout(this._reminder.bind(this), remaining);
            }
        }
    };

    Timer.prototype.clear = function (ev, cellModel) {
        global.clearTimeout(this.timerId);
    };

    Timer.prototype.getValue = function () {
        if (!this.isRunning)
            return this.elapsed;

        return Date.now() - this.startDate;
    };

    Timer.prototype._reminder = function () {
        this.callback();
        global.clearTimeout(this.timerId);
        this.timerId = global.setTimeout(this._reminder.bind(this), this.delay);
    };


}(this));
